package com.hyacinth.cloudnote.modules.note.service;

import com.hyacinth.cloudnote.common.exception.ExceptionHolder;
import com.hyacinth.cloudnote.modules.note.model.Tag;
import com.hyacinth.cloudnote.modules.note.repository.NoteTagRepository;
import com.hyacinth.cloudnote.modules.note.repository.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000000001;
import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000001001;

/**
 * Tag实体对应的业务逻辑Service实现类
 * @author zhangfb
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TagService {

    @Autowired
    private TagRepository tagRepository;
    @Autowired
    private NoteTagRepository noteTagRepository;
    @Autowired
    private FavoriteService favoriteService;

    public Tag save(Tag model) {
        // 校验标签名
        boolean existsTagName;
        if (model.isNew()) {
            existsTagName = tagRepository.existsByName(model.getName());
        } else {
            existsTagName = tagRepository.existsByNameAndIdNot(model.getName(), model.getId());
        }
        if (existsTagName) {
            throw ExceptionHolder.serviceException(E1000001001, model.getName());
        }
        return tagRepository.save(model);
    }

    public void delete(UUID id) {
        Tag tag = tagRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(E1000000001, "标签-" + id));
        // 删除收藏记录
        favoriteService.deleteByTag(tag);
        // 删除NoteTag
        noteTagRepository.deleteAllByTag(tag);
        // 删除标签
        tagRepository.delete(tag);
    }
}
